import re


def format_txt(text):
    # 去除多余的空格和换行符
    formatted_text = text.replace("\n", "").replace(" ", "")
    return formatted_text


def format_txt_eng(text):
    # 去除多余的空格和换行符
    formatted_text = text.replace("\n", "").replace("\\", "")
    return formatted_text


# 替换参数的函数
def replace_parameters(match, parameters):
    parameter_name = match.group(1)
    return str(parameters.get(parameter_name, ""))


# 替换链接中的参数
def format_url_by_template(template, parameters):
    # 使用正则表达式替换参数
    url = re.sub(r"{{(.*?)}}", lambda x: replace_parameters(x, parameters), template)
    return url


def camel_to_snake(name):
    # 使用正则表达式将驼峰命名法转换为蛇形命名法
    s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
    return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()


def convert_dict_keys(dictionary):
    new_dict = {}
    for key, value in dictionary.items():

        # 将驼峰命名法的键转换为蛇形命名法
        new_key = camel_to_snake(key)
        new_dict[new_key] = value
        if type(new_dict[new_key]) is dict:
            new_dict[new_key] = convert_dict_keys(new_dict[new_key])

    return new_dict


if __name__ == "__main__":
    # text = "  This is some text\'s with  extra  \"spaces.  \n And new lines.\n"
    # print(format_txt_eng(text))

    # 原始链接模板
    template = "{{host}}?s={{search_key}}"

    # 要替换的参数及其对应的值（字典形式）
    params = {
        "host": "https://xlust.org",
        "page_index": 1,
        "search_key": "萌汉药"
    }
    print(format_url_by_template(template, params))

    camel_case_variable = "myCamelCaseVariable"
    snake_case_variable = camel_to_snake(camel_case_variable)
    print(snake_case_variable)
